package com.example.demo.Interceptor;

import com.example.demo.config.ApiException;
import com.example.demo.config.RetEnum;
import com.example.demo.service.RedisService;
import com.example.demo.vo.user.UserInfo;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * 请求拦截器
 */
public class RequestInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    static List<String> freeList = new ArrayList<>();

    static {
        try {
            /**
             * 可以通行的接口链接
             */
            freeList.add("/user/login");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        boolean isFree = freeList.stream().filter(e -> requestURI.contains(e)).count() > 0;
        /**
         * 不需要登录的就能操作的接口直接放行
         */
        if (isFree) {
            return true;
        }
        /**
         * 从请求头获取token的值（该值从登录后的token获取，请求需要登录后才能操作的接口需要放在请求头上 token--值）
         */
        String loginToken = request.getHeader("loginToken");
        UserInfo userInfo = redisService.getUserInfo(loginToken);
        if (userInfo == null) {
            throw new ApiException(RetEnum.Token_Expire);
        }
        /**
         * 存储提供给需要获取用户信息的接口（UserInfo userInfo = (UserInfo) request.getAttribute("userInfo")）
         */
        request.setAttribute("userInfo", userInfo);
        return true;
    }
}
